package ldh.im.fxbase.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class LoggerUtil {

    private static final String LOG_FILE = "imgui";
    private volatile static Logger LOGGER = null;

    public static Logger getFileLogger(Class clazz) {
        if (LOGGER == null) {
            synchronized (LoggerUtil.class) {
                if (LOGGER == null) {
                    LOGGER = Logger.getLogger(clazz.getName());
                    String logFile = getCurrentFile() + LOG_FILE;
                    format(LOGGER, "yyyyMMdd", logFile);
                }
            }
        }
        return LOGGER;
    }

    private static void format(Logger logger, String StrFormat, String logFile) {
        SimpleDateFormat format = new SimpleDateFormat(StrFormat);
        try {
            FileHandler fh = new FileHandler(logFile + "_" + format.format(Calendar.getInstance().getTime()) + ".log", true);
            fh.setFormatter(new SimpleFormatter());
            logger.addHandler(fh);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getCurrentFile() {
        String dir = System.getProperty("user.dir") + "/logs/";
        File file = new File(dir);
        while(!file.exists()) {
            file.mkdir();
        }
        return dir;
    }
}
